package com.egene.tw.activity.wiki;

import android.content.Intent;
import android.view.View;

import com.egene.tw.R;
import com.egene.tw.api.EgeneApi;
import com.egene.tw.base.BaseRecycleViewFragment;
import com.egene.tw.base.RecycleBaseAdapter;
import com.egene.tw.model.WikiArticle;
import com.egene.tw.model.net.ResponseList;
import com.egene.tw.utils.JsonUtil;
import com.egene.tw.utils.MToast;
import com.google.gson.reflect.TypeToken;
import com.loopj.android.http.AsyncHttpResponseHandler;

import org.androidannotations.annotations.EFragment;
import org.androidannotations.annotations.UiThread;
import org.apache.http.Header;

import java.util.List;

@EFragment
public class ChildHealthFragment extends BaseRecycleViewFragment {
    public ChildHealthFragment() {
        // Required empty public constructor
    }

    @Override
    protected RecycleBaseAdapter getListAdapter() {
        return new WikiRecycleAdapter();
    }


    @Override
    protected void sendRequestData() {
        fetchList();
    }

    void fetchList() {
        EgeneApi.getWikiChildList(mCurrentPage, new AsyncHttpResponseHandler() {
            @Override
            public void onSuccess(int statusCode, Header[] headers, byte[] responseBody) {
                if(mRecycleView == null){
                    return;
                }
                ResponseList<WikiArticle> response = JsonUtil.toList(responseBody,
                        new TypeToken<ResponseList<WikiArticle>>() {
                        }.getType());
                if (response != null) {
//                    updateList(response.getData());
                    List<WikiArticle> articleList = response.getData();
                    if(articleList != null){
                        updateList(articleList);
                    }else{
                        executeNoMore();
                    }
                }
            }

            @Override
            public void onFailure(int statusCode, Header[] headers, byte[] responseBody, Throwable error) {
                executeOnLoadFinish();
                MToast.show(R.string.no_network);
            }
        });
    }


    @UiThread
    void updateList(List<WikiArticle> list) {
        if (mCurrentPage == START_PAGE_INDEX) {
            mAdapter.clear();
        }
        mAdapter.addData(list);
        executeOnLoadFinish();
        if(list.size() < PAGE_SIZE){
            executeNoMore();
        }else{
            executeOnLoadFinish();
        }
    }

    @Override
    protected void onItemClick(View view, int position) {
        WikiArticle article = (WikiArticle) mAdapter.getItem(position);
        Intent intent = new Intent(getActivity(), WikInfoActivity_.class);
        intent.putExtra(WikInfoActivity.ID, article.getId());
        startActivity(intent);
    }
}